package gazzera.node.core.plugins.download;

import gazzera.gui.*;
import gazzera.node.core.*;
import gazzera.utils.*;

import java.io.*;
import java.security.*;


public class VerificationTask implements Task
{

	public FileID fileId;
	public File file;
	public boolean valid;
	public boolean interrupted = false;
	private byte[] buf = new byte[1024*20];	
	public Hash calculatedHash = null;
	
	public VerificationTask(FileID fileId, File file)
	{
		super();
		this.fileId = fileId;
		this.file = file;
	}

	@Override
	public void interrupt()
	{
		interrupted = true;
	}

	private Hash hashFile(File f) throws Exception
	{
		MessageDigest m = MessageDigest.getInstance("SHA1");
		FileInputStream fis = new FileInputStream(f);
		try
		{
			int r = fis.read(buf);
			while (r>=0)
			{
				m.update(buf, 0, r);
				r = fis.read(buf);
				if(interrupted) return Hash.EMPTY;
			}
			return new Hash(m.digest());
		}
		finally
		{
			fis.close();
		}
	}
	
	@Override
	public Object run(GuiInterface gui) throws Exception
	{
		calculatedHash = hashFile(file);
		valid = false;
		if(fileId instanceof Hash)
		{
			valid = calculatedHash.equals(fileId);
		}
		else if(fileId instanceof UserFileID)
		{
			// we don't have the hash, suppose it's ok
			valid = true;
		}
		return false;
	}

}
